package ext.generic.part;

import com.ptc.core.components.forms.*;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.misc.NmContext;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import java.util.*;

import org.apache.log4j.Logger;

import wt.doc.WTDocument;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.WTReference;
import wt.fc.collections.WTArrayList;
import wt.fc.collections.WTCollection;

import wt.log4j.LogR;

import wt.part.WTPart;
import wt.part.WTProductInstance2;

import wt.session.SessionHelper;

import wt.util.*;

import wt.workflow.engine.ProcessData;
import wt.workflow.work.*;

import wt.part.*;

import wt.fc.*;

import wt.lifecycle.LifeCycleManaged;

import wt.session.SessionServerHelper;

/**
 * 零部件流程中"移除"随签对象的action响应方法类
 */
public class RemoveReviewObjsFormProcessor extends DefaultObjectFormProcessor
{
    private static final String RESOURCE = "com.ptc.netmarkets.util.utilResource";
    private static final Logger log;
    protected String redirectURL;
    private static boolean VERBOSE = false;
    private static String CLASSNAME = RemoveReviewObjsFormProcessor.class.getName();
    static
    {
        try
        {
            log = LogR.getLogger(ext.generic.part.RemoveReviewObjsFormProcessor.class.getName());
            VERBOSE = (WTProperties.getLocalProperties()).getProperty("ext.generic.part.verbose", false);
        }
        catch (Exception exception)
        {
            throw new ExceptionInInitializerError(exception);
        }
    }

    public RemoveReviewObjsFormProcessor()
    {
        redirectURL = null;
    }
    /**
     *主要的数据处理方法
     * @param nmcommandbean
     * @param list
     * @return
     * @throws WTException
     */
    public FormResult doOperation(NmCommandBean nmcommandbean, List list) throws WTException
    {
//        Vector reviewObjs = new Vector();  
    	WTArrayList batchReviewDocs = new WTArrayList();
    	NmOid nmoid = nmcommandbean.getPrimaryOid();
        WorkItem workitem = (WorkItem) nmoid.getRef();
        WfAssignedActivity wfassignedactivity = (WfAssignedActivity) workitem.getSource().getObject();
        ProcessData context = wfassignedactivity.getContext();
    	batchReviewDocs = (WTArrayList) (context.getValue("reviewObjs"));
    	//Object oj=batchReviewDocs.getPersistable(0);    	
    	List reviewObjs = new ArrayList();
        java.util.Locale locale = SessionHelper.getLocale();
        FormResult formresult = new FormResult();
        formresult.setStatus(FormProcessingStatus.SUCCESS);
       
        if (nmcommandbean.getSelected().size() == 0)
        {
            FeedbackMessage feedbackmessage =
                new FeedbackMessage(FeedbackType.FAILURE, locale, new WTMessage("com.ptc.netmarkets.util.utilResource", "NO_OBJECT_SELECTED", null), null, new LocalizableMessage[]
                    { new WTMessage("com.ptc.netmarkets.util.utilResource", "NO_OBJECT_SELECTED", null) });
            formresult.addFeedbackMessage(feedbackmessage);
            formresult.setStatus(FormProcessingStatus.FAILURE);
            formresult.setNextAction(FormResultAction.REFRESH_CURRENT_PAGE);
            throw new WTException("未选择任何随迁对象!");
            //return formresult;
        }
        wt.fc.Persistable persistable = nmcommandbean.getPrimaryOid().getWtRef().getObject();       
        if (persistable instanceof WorkItem)
        {
            WorkItem workItem = (WorkItem) persistable;
            WfAssignedActivity wfAssignedActivity = (WfAssignedActivity) workItem.getSource().getObject();
            reviewObjs = (List) (wfAssignedActivity.getContext().getValue("reviewObjs"));
            WTPart pbo = (WTPart) (wfAssignedActivity.getContext().getValue("primaryBusinessObject"));
            boolean flag = doRemoveOperation(nmcommandbean, pbo, reviewObjs);
            for(int j=0;j<reviewObjs.size();j++){
            	ObjectReference obj=(ObjectReference)reviewObjs.get(j);
            	Persistable per=(Persistable)obj.getObject();           	
            	System.out.println("***************************reviewObjs="+per);
            }
            
            if (flag)
            {
                wfAssignedActivity.getContext().setValue("reviewObjs", reviewObjs);
                PersistenceHelper.manager.save(wfAssignedActivity);
                PersistenceHelper.manager.save(workItem);
            }            
        }
        formresult.setNextAction(FormResultAction.REFRESH_CURRENT_PAGE);
        super.doOperation(nmcommandbean, list);
        return formresult;
    }

    protected FormResult setRefreshInfo(FormResult formresult, NmCommandBean nmcommandbean, List list) throws WTException
    {
        DynamicRefreshInfo dynamicrefreshinfo = new DynamicRefreshInfo();
        dynamicrefreshinfo.setLocation(nmcommandbean.getActionOid());
        dynamicrefreshinfo.setOid(nmcommandbean.getActionOid());
        NmCommandBean _tmp = nmcommandbean;
        dynamicrefreshinfo.setAction("U");
        formresult.addDynamicRefreshInfo(dynamicrefreshinfo);
        return formresult;
    }

    /**
     *移除随签对象；对于”返回“状态的随签对象，改状态为“正在工作”；对于非”正在工作“状态的随签对象，清除”随签流程“属性值
     */
    public static boolean doRemoveOperation(NmCommandBean nmcommandbean, WTPart pbo, List reviewObjs) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doRemoveOperation()");
        boolean flag = false;
        ArrayList list = nmcommandbean.getSelected();
        if (VERBOSE)
            System.out.println("doRemoveOperation   " + list.size() + " objs ared selected!");
        boolean flag1 = SessionServerHelper.manager.setAccessEnforced(false);
        try
        {
            for (int i = 0; i < list.size(); i++)
            {
                NmContext nmcontext = (NmContext) list.get(i);
                WTObject wtobject = (WTObject) nmcontext.getTargetOid().getWtRef().getObject();
                if (VERBOSE)
                    System.out.println("    Process " + wtobject.getDisplayIdentity() + ".");
              //modified beign 
                if(pbo.equals(wtobject)){
                	throw new WTException("主对象"+pbo.getName()+"不能被移除!");
                }
              //moidfied end
                if (!pbo.equals(wtobject))
                {
                    reviewObjs.remove(wtobject);
                    String state = ((LifeCycleManaged) wtobject).getLifeCycleState().toString();
                    //如果状态是”重新工作“，则需要将状态设为”正在工作“
                    if (state.equals("REWORK"))
                    {
                        wtobject = (WTObject) ext.com.workflow.WorkflowUtil.setLifeCycleState((LifeCycleManaged) wtobject, "INWORK");
                    }
                    //对于非”正在工作“状态的随签对象，清除”随签流程“属性值
                    if (!state.equals("INWORK"))
                    {
                    	wtobject = PartWorkflowUtil.clearHistoricalIBA(wtobject, "revise");
                    }
                    flag = true;
                    if (VERBOSE)
                        System.out.println("        " + wtobject.getIdentity() + " is removed from reviewObjs!");
                }
            }
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag1);
        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doRemoveOperation()--flag=" + flag);
        return flag;
    }
}
